<template>
  <div class="Avatar-container">
    <img :src="img"
      ref="image">
    <div class="toolbar">
      <div class="cancel"
        @click="$emit('close')">取消</div>
      <div class="confirm"
        @click="onConfirm">完成</div>
    </div>
  </div>
</template>

<script>
import 'cropperjs/dist/cropper.css'
import Cropper from 'cropperjs'
import { editUserPhoto } from '@/api/user'
export default {
  name: 'SetAvatar',
  props: {
    img: {
      type: [String, Object],
      required: true
    }
  },
  data () {
    return {
      cropper: null
    }
  },
  mounted () {
    const image = this.$refs.image
    this.cropper = new Cropper(image, {
      viewMode: 1, // 只能在裁剪的图片范围内移动
      dragMode: 'move', // 画布可以移动
      aspectRatio: 1, // 裁剪区默认正方形
      autoCropArea: 1, // 自动调整裁剪图片
      cropBoxMovable: false, // 禁止裁剪区移动
      cropBoxResizable: false, // 禁止裁剪区缩放
      background: false // 关闭默认背景
    })
    // console.log(this.cropper)
  },
  methods: {
    onConfirm () {
      this.$toast.loading({
        message: '头像上传中...',
        forbidClick: true, // 禁止背景点击
        duration: 0 // 持续展示
      })

      // 服务端剪切方式
      // console.log(this.cropper.getData())
      // 客户端剪切方式
      this.cropper.getCroppedCanvas().toBlob(async blob => {
        try {
          // 错误的用法
          // 如果接口要求 Content-Type 是 application/json
          // 则传递普通 JavaScript 对象
          // const { data: res } = await editUserPhoto({
          //   photo: blob
          // })
          // console.log(blob)

          // 正确的用法
          // 如果接口要求 Content-Type 是 multipart/form-data
          // 则你必须传递 FormData 对象
          const formData = new FormData()
          formData.append('photo', blob)
          const { data: res } = await editUserPhoto(formData)
          // console.log(res.data.photo)
          // 1、关闭弹层
          this.$emit('close')
          // 2、更新视图
          this.$emit('update-photo', res.data.photo)
          // 3、提示成功
          this.$toast.success('更新成功')
        } catch (err) {
          // console.log(err)
          // 提示失败
          this.$toast.fail('更新失败')
        }
      })
    }
  }
}
</script>

<style scoped lang="less">
.Avatar-container {
  background-color: #000;
  height: 100%;
  img {
    display: block;
    max-width: 100%;
  }
  .toolbar {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    display: flex;
    justify-content: space-between;
    .cancel,
    .confirm {
      display: flex;
      justify-content: center;
      align-items: center;
      width: 90px;
      height: 90px;
      font-size: 30px;
      color: #fff;
    }
  }
}
</style>
